import fallback from "@/components/fallback"
import { Suspense, useEffect } from "react"
import useMainStore from "@/store"
import { ConfigProvider, message, theme } from "antd"
import eventBus from "@/utils/event-bus"
import debounce from "@/utils/debounce"
import { ThemeProvider } from "@/contexts/theme-provider"
import { ThemeContext } from "@/contexts/theme-context"
import { RouterRefreshProvider } from "@/contexts/refresh-provider"
import { RouterProvider } from "react-router"
import { router } from "@/router"


function App() {
	const [messageApi, contextHolder] = message.useMessage();
	const { token } = useMainStore()
	console.log(token);
	// 监听全局错误信息
	useEffect(() => {
		const messageHandler = debounce((msg: string) => {
			messageApi.open({
				type: 'error',
				content: msg,
			});
		}, 500, true)

		eventBus.on('error-message', (msg: string) => {
			messageHandler(msg)
		})
		return () => {
			eventBus.off('error-message', messageHandler)
		}
	}, [])
	return (
		<>
			<ThemeProvider>
				<ThemeContext.Consumer>
					{({ themeType }) => (
						<ConfigProvider
							theme={{
								algorithm: themeType === 'dark' ? theme.darkAlgorithm : theme.defaultAlgorithm,
							}}
						>
							{contextHolder}
							<Suspense fallback={fallback}>
								<RouterRefreshProvider>
									<RouterProvider router={router} />
								</RouterRefreshProvider>
							</Suspense>
						</ConfigProvider>
					)}
				</ThemeContext.Consumer>
			</ThemeProvider>
		</>
	)
}

export default App
